/**
 * 
 */
package com.xbang.attendance.web.action.warehouse.inventoryrecord;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.xbang.attendance.entity.stock.Inventory;
import com.xbang.attendance.entity.stock.InventoryRecord;
import com.xbang.attendance.entity.system.Region;
import com.xbang.attendance.entity.system.Warehouse;
import com.xbang.attendance.service.InventoryService;
import com.xbang.attendance.service.RegionService;
import com.xbang.attendance.service.SystemService;
import com.xbang.attendance.service.WarehouseService;
import com.xbang.attendance.utils.Constants;
import com.xbang.attendance.utils.DateUtil;
import com.demo2do.lighturl.annotation.Action;
import com.xbang.core.dao.search.component.SearchComponent;
import com.xbang.core.page.Result;
import com.xbang.core.struts.support.SearchActionSupport;
import com.xbang.core.utils.DateUtils;

import enumeration.InventoryOperation;

/**
 * @author dev.zhang
 */
public class Index extends SearchActionSupport {

	private static final long serialVersionUID = 2886204759816132683L;

	@Autowired
	private WarehouseService warehouseService;
	
	@Autowired
	private SystemService systemService;

	private Map requestMap;
	@Autowired
	private RegionService regionService;
	private Warehouse warehouse;

	private List<Region> regions = new ArrayList<Region>();

	private List<Warehouse> warehouses = new ArrayList<Warehouse>();

	private Integer warehouseId, year, month, productId;
	
	
	private Date beginDate;
	private Date endDate;
	//private String code;
	
	private String beginDateString;
	private String endDateString;
	@Autowired
	private InventoryService inventoryService;

	private InventoryRecord inventoryRecord;

	private List<InventoryRecord> inventoryRecords = new ArrayList<InventoryRecord>();

	private String salesOrderNumber;

	private Inventory inventory;
	private String lastInventoryOperation;

	private List<Object[]> inventoryRecordObjects = new ArrayList<Object[]>();

	@Action("/warehouse/inventoryrecord/out/${warehouseId}/${productId}/")
	public String outList() throws Exception {

		searchInventoryExchangeByCondition(InventoryOperation.OUT);

		return "out-index";
	}

	@Action("/warehouse/inventoryrecord/replenishment/${warehouseId}/${productId}/")
	public String replenishmentList() throws Exception {

		searchInventoryExchangeByCondition(InventoryOperation.REPLENISHMENT);

		return "replenishment-index";
	}

	@Action("/warehouse/inventoryrecord/waresearch/${warehouseId}/view")
	public String viewWarehouseStock() throws Exception {

		if (warehouseId != null) {
			warehouse = (Warehouse) inventoryService.get(Warehouse.class, warehouseId);
		}

		return searhcWarehou();
	}
	
	@Action("/warehouse/inventoryrecord/search/filter/do")
	public String doSearchFilter()  throws Exception  {
		
//		if (code != null) {
//			warehouse = (Warehouse)warehouseService.getWarehouseByCode(code);
//			
////			year = Integer.parseInt(timepart_.split("-")[0]);
////			month = Integer.parseInt(timepart_.split("-")[1]);
//		}
//		
		
		return searhcWarehou();
	}
	
	@Action("/warehouse/inventoryrecord/waresearch/salesorder")
	public String viewSalesOrder() throws Exception {

		
		if(salesOrderNumber.isEmpty()){
			return "sales-order-index";
		}
		SearchComponent tmpSearchComponent = new SearchComponent();

		tmpSearchComponent.addSearchElement("eq.inventoryrecord.poNumber", salesOrderNumber);

		Result result = inventoryService.searchByPage("FROM InventoryRecord inventoryrecord WHERE 1 = 1 ", tmpSearchComponent, page);

		
		inventoryRecords = result.getItems();
		
		if (null != inventoryRecords && !inventoryRecords.isEmpty()){
			inventoryRecord = inventoryRecords.get(0);
			warehouse = inventoryRecord.getWarehouse();
		}
		
		page = result.getPage();

		return "sales-order-index";
	}

	@Action("/warehouse/inventoryrecord/list/search")
	public String searchWarehouse() throws Exception {

		//regions = regionService.getAKZRegion();
		warehouses = inventoryService.getObjects(Warehouse.class);

		return "list-search";
	}
	
	@Action("/warehouse/inventoryrecord/list/toexport")
	public String toexprot() throws Exception {

		//regions = regionService.getAKZRegion();
		//warehouses = inventoryService.getObjects(Warehouse.class);

		return "list-dowload";
	}
	@Action("/warehouse/inventoryrecord/list/exprot")
	public String exprot()  throws Exception  {
		String webPath = ServletActionContext.getRequest().getRealPath("//download//warehouse//stock");
		HttpServletRequest request = ServletActionContext.getRequest();
		String urlPath = request.getRequestURL().toString();
		String contextPath = request.getContextPath();
		String contextURL = urlPath.split(contextPath)[0] + contextPath;
		String exportFile = contextURL ;
		Warehouse warehouse =warehouseService.getWarehouseByCode(code);
		try {
			exportFile += "/download/warehouse/stock/" + warehouseService.genericExcelFile(webPath,lastInventoryOperation,warehouse.getId(),beginDate,endDate);	
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return "r:" + exportFile;
	}
	


	@Action("/warehouse/inventoryrecord/waresearch")
	public String searhcWarehou() throws Exception {
			
			//searchComponent.getParameters().get("");
			String hql = "FROM InventoryRecord inventoryrecord WHERE 1=1";
			//if()
			String code = (String) searchComponent.getParameters().get("eqInventoryrecordWarehouseCode");
			warehouse = warehouseService.getWarehouseByCode(code);
			
			if(lastInventoryOperation!= null && !lastInventoryOperation.isEmpty()){
				searchComponent.addSearchElement("eq.inventoryrecord.lastInventoryOperation", InventoryOperation.valueOf(lastInventoryOperation));
			}
			
			//searchComponent.addSearchElement("gt.inventoryrecord.operationDate",DateUtil.parseDate(DateUtil.getPreviousDay(beginDate), DateUtil.DATETIME_FORMAT) );
			//searchComponent.addSearchElement("lt.inventoryrecord.operationDate",DateUtil.parseDate(DateUtil.getNextDay(endDate),DateUtil.DATETIME_FORMAT));
			//searchComponent.addSearchElement("eq.inventoryrecord.warehouse.code", warehouse.getCode());
			Result result = systemService.searchByPage(hql, searchComponent, page);
			inventoryRecords = result.getItems();
			
//			
//			if(!inventoryRecords.isEmpty())
//				warehouse = inventoryRecords.get(0).getWarehouse();
//			//Date soDate = DateUtils.parseDate("" + year + "-" + month + "-25", "yyyy-MM-dd");
//			searchComponent.resetGroupSentence();
//			searchComponent.resetOrderSentence();
//			searchComponent.resetWhereSentence();
//			//System.out.println(beginDate +" ==="+ endDate);
//			//System.out.println(DateUtils.format(beginDate, "yyyy-MM-dd") +"   "+ DateUtils.format(endDate, "yyyy-MM-dd"));
//			
//			//beginDate = DateUtils.parseDate(DateUtils.format(beginDate, "yyyy-MM-dd"), "yyyy-MM-dd");
//			//endDate = DateUtils.parseDate(DateUtils.format(endDate, "yyyy-MM-dd"), "yyyy-MM-dd");
//			
//			
//			//System.out.println(DateUtils.format(beginDate, "yyyy-MM-dd") +"   "+ DateUtils.format(endDate, "yyyy-MM-dd"));
//			//System.out.println(DateUtil.parseDate(DateUtil.getPreviousDay(beginDate), DateUtil.DATETIME_FORMAT));
//			//System.out.println(DateUtil.parseDate(DateUtil.getNextDay(endDate), DateUtil.DATETIME_FORMAT));
//			
//			searchComponent.addSearchElement("gt.inventoryrecord.operationDate",DateUtil.parseDate(DateUtil.getPreviousDay(beginDate), DateUtil.DATETIME_FORMAT) );
//			searchComponent.addSearchElement("lt.inventoryrecord.operationDate",DateUtil.parseDate(DateUtil.getNextDay(endDate),DateUtil.DATETIME_FORMAT));
//			searchComponent.addSearchElement("eq.inventoryrecord.warehouse.code", warehouse.getCode());
//		} else {
//			return "r:/warehouse/inventoryrecord/list/search";
//		}
//
//		String hqlSentence = "FROM Warehouse warehouse WHERE 1 = 1 ";
//		String parameterKey = "eqInventoryRecordWarehouseCode";
//
//		Object value = getSearchParameterValue(parameterKey);
//		if (value != null) {
//			SearchComponent tmpSearchComponent = new SearchComponent();
//			tmpSearchComponent.getParameters().put("eqWarehouseCode", value);
//			tmpSearchComponent.getWhereSentences().put("eq.warehouse.code", " AND (warehouse.code = :eqWarehouseCode)");
//
//			List objects = inventoryService.searchForList(hqlSentence, tmpSearchComponent);
//			if (objects != null && !objects.isEmpty()) {
//				warehouse = (Warehouse) objects.get(0);
//			}
//		}
//
//		String tmpHqlSentence = "SELECT inventoryrecord.product.productCategory.categoryName," + "inventoryrecord.product.productCode ,"
//				+ "inventoryrecord.product.productName "
//				+ ",CASE WHEN inventoryrecord.lastInventoryOperation = 'OUT' THEN sum(inventoryrecord.amount) END as outSum_"
//				+ ",CASE WHEN inventoryrecord.lastInventoryOperation = 'REPLENISHMENT' THEN sum(inventoryrecord.amount) END as replenishmentSum_"
//				+ ",CASE WHEN inventoryrecord.lastInventoryOperation = 'TRANSFERRED' THEN sum(inventoryrecord.amount) END as transferredSum_"
//				+ ",CASE WHEN inventoryrecord.lastInventoryOperation = 'TURE_OUT' THEN sum(inventoryrecord.amount) END as trueOutSum_"
//				+ ",sum(inventoryrecord.amount) as sum1_ " + "FROM InventoryRecord inventoryrecord WHERE 1 = 1 ";
//
//		SearchComponent tmpSearchComponent = new SearchComponent();
//		tmpSearchComponent.getWhereSentences().putAll(searchComponent.getWhereSentences());
//		tmpSearchComponent.getParameters().putAll(searchComponent.getParameters());
//		tmpSearchComponent.addSearchElement("groupby.inventoryrecord.product.productCategory.categoryName", "");
//		tmpSearchComponent.addSearchElement("groupby.inventoryrecord.product.productCode", "");
//		tmpSearchComponent.addSearchElement("groupby.inventoryrecord.product.productName", "");
//		Result result = inventoryService.searchByPage(tmpHqlSentence, tmpSearchComponent, page);
//		inventoryRecordObjects = result.getItems();
//
//		tmpHqlSentence = "SELECT inventoryrecord.lastInventoryOperation,inventoryrecord.product.productCategory.categoryName,"
//				+ "inventoryrecord.product.productCode ,inventoryrecord.product.id " + ",sum(inventoryrecord.amount) as sum1_ "
//				+ "FROM InventoryRecord inventoryrecord WHERE 1 = 1 ";
//		tmpSearchComponent.addSearchElement("groupby.inventoryrecord.product.id", "");
//		tmpSearchComponent.addSearchElement("groupby.inventoryrecord.lastInventoryOperation", "");
//
//		List<Object[]> tmpLists = inventoryService.searchForList(tmpHqlSentence, tmpSearchComponent);
//		
//
//		if (inventoryRecordObjects != null && !inventoryRecordObjects.isEmpty() && tmpLists != null && !tmpLists.isEmpty()) {
//			for (Object[] inventoryRecordObject : inventoryRecordObjects) {
//				inventoryRecordObject[3] = new BigDecimal(0);
//				inventoryRecordObject[4] = new BigDecimal(0);
//				inventoryRecordObject[5] = new BigDecimal(0);
//				inventoryRecordObject[6] = new BigDecimal(0);
//				for (Object[] tmpInventoryRecordObject : tmpLists) {
//					if (inventoryRecordObject[1].toString().equals(tmpInventoryRecordObject[2].toString())) {
//						if (tmpInventoryRecordObject[4] == null) {
//							tmpInventoryRecordObject[4] = new BigDecimal(0);
//						}
//
//						if (tmpInventoryRecordObject[0].toString().equals(InventoryOperation.OUT.toString())) {
//							inventoryRecordObject[3] = ((BigDecimal) inventoryRecordObject[3]).add((BigDecimal) tmpInventoryRecordObject[4]);
//						} 
//						if(tmpInventoryRecordObject[0].toString().equals(InventoryOperation.TRANSFERRED.toString())){
//							inventoryRecordObject[4] = ((BigDecimal) inventoryRecordObject[4]).add((BigDecimal) tmpInventoryRecordObject[4]);
//						}
//						if(tmpInventoryRecordObject[0].toString().equals(InventoryOperation.TURE_OUT.toString())){
//							inventoryRecordObject[5] = ((BigDecimal) inventoryRecordObject[5]).add((BigDecimal) tmpInventoryRecordObject[4]);
//						}
//						if(tmpInventoryRecordObject[0].toString().equals(InventoryOperation.REPLENISHMENT.toString())){
//							inventoryRecordObject[6] = ((BigDecimal) inventoryRecordObject[6]).add((BigDecimal) tmpInventoryRecordObject[4]);
//						}
//						//sys
//						inventoryRecordObject[7] = tmpInventoryRecordObject[3];
//					}  
//
//				
//			}
//		}

		page = result.getPage();
		
		return "index";

	}

	/**
	 * 
	 */
	private void searchInventoryExchangeByCondition(InventoryOperation inventoryOperation)throws Exception {
		
			warehouse = (Warehouse) inventoryService.get(Warehouse.class, warehouseId);

			SearchComponent tmpSearchComponent = new SearchComponent();

			//Date geqDate = DateUtils.parseDate("" + year + "-" + month + "-25", "yyyy-MM-dd");
			//Date leqDate = DateUtils.addDateEnum(geqDate, -1, Calendar.MONTH);
			
			//System.out.println(beginDate +" ==="+ endDate);
			

			tmpSearchComponent.addSearchElement("gt.inventoryrecord.operationDate", DateUtil.parseDate(DateUtil.getPreviousDay(beginDate), DateUtil.DATETIME_FORMAT));
			tmpSearchComponent.addSearchElement("lt.inventoryrecord.operationDate", DateUtil.parseDate(DateUtil.getNextDay(endDate), DateUtil.DATETIME_FORMAT));
			tmpSearchComponent.addSearchElement("eq.inventoryrecord.warehouse.id", warehouseId);
			tmpSearchComponent.addSearchElement("eq.inventoryrecord.product.id",productId);
			tmpSearchComponent.addSearchElement("eq.inventoryrecord.lastInventoryOperation", inventoryOperation);

			Result result = inventoryService.searchByPage("FROM InventoryRecord inventoryrecord WHERE 1 = 1 ", tmpSearchComponent, page);

			
			inventoryRecords = result.getItems();
			
			if (null != inventoryRecords && !inventoryRecords.isEmpty()){
				inventoryRecord = inventoryRecords.get(0);
				
			}
			page = result.getPage();
			// searchComponent.
	}

	/**
	 * @return the inventoryRecords
	 */
	public List<InventoryRecord> getInventoryRecords() {
		return inventoryRecords;
	}

	/**
	 * @param inventoryRecords
	 *            the inventoryRecords to set
	 */
	public void setInventoryRecords(List<InventoryRecord> inventoryRecords) {
		this.inventoryRecords = inventoryRecords;
	}

	/**
	 * @param systemService
	 *            the systemService to set
	 */
	public void setSystemService(SystemService systemService) {
		this.systemService = systemService;
	}

	/**
	 * @param inventoryService
	 *            the inventoryService to set
	 */
	public void setInventoryService(InventoryService inventoryService) {
		this.inventoryService = inventoryService;
	}

	public void resetCustomerSearchCriteria() {

	}

	/**
	 * @return the warehouse
	 */
	public Warehouse getWarehouse() {
		return warehouse;
	}

	/**
	 * @param warehouse
	 *            the warehouse to set
	 */
	public void setWarehouse(Warehouse warehouse) {
		this.warehouse = warehouse;
	}

	/**
	 * @return the warehouses
	 */
	public List<Warehouse> getWarehouses() {
		return warehouses;
	}

	/**
	 * @param warehouses
	 *            the warehouses to set
	 */
	public void setWarehouses(List<Warehouse> warehouses) {
		this.warehouses = warehouses;
	}

	/**
	 * @return the salesOrderNumber
	 */
	public String getSalesOrderNumber() {
		return salesOrderNumber;
	}

	/**
	 * @param salesOrderNumber
	 *            the salesOrderNumber to set
	 */
	public void setSalesOrderNumber(String salesOrderNumber) {
		this.salesOrderNumber = salesOrderNumber;
	}

	/**
	 * @return the inventoryRecord
	 */
	public InventoryRecord getInventoryRecord() {
		return inventoryRecord;
	}

	/**
	 * @param inventoryRecord
	 *            the inventoryRecord to set
	 */
	public void setInventoryRecord(InventoryRecord inventoryRecord) {
		this.inventoryRecord = inventoryRecord;
	}

	/**
	 * @return the regions
	 */
	public List<Region> getRegions() {
		return regions;
	}

	/**
	 * @param regions
	 *            the regions to set
	 */
	public void setRegions(List<Region> regions) {
		this.regions = regions;
	}

	/**
	 * @return the warehouseId
	 */
	public Integer getWarehouseId() {
		return warehouseId;
	}

	/**
	 * @param warehouseId
	 *            the warehouseId to set
	 */
	public void setWarehouseId(Integer warehouseId) {
		this.warehouseId = warehouseId;
	}

	/**
	 * @return the year
	 */
	public Integer getYear() {
		return year;
	}

	/**
	 * @param year
	 *            the year to set
	 */
	public void setYear(Integer year) {
		this.year = year;
	}

	/**
	 * @return the month
	 */
	public Integer getMonth() {
		return month;
	}

	/**
	 * @param month
	 *            the month to set
	 */
	public void setMonth(Integer month) {
		this.month = month;
	}

	/**
	 * @return the inventoryRecordObjects
	 */
	public List<Object[]> getInventoryRecordObjects() {
		return inventoryRecordObjects;
	}

	/**
	 * @param inventoryRecordObjects
	 *            the inventoryRecordObjects to set
	 */
	public void setInventoryRecordObjects(List<Object[]> inventoryRecordObjects) {
		this.inventoryRecordObjects = inventoryRecordObjects;
	}

	/**
	 * @return the productId
	 */
	public Integer getProductId() {
		return productId;
	}

	/**
	 * @param productId
	 *            the productId to set
	 */
	public void setProductId(Integer productId) {
		this.productId = productId;
	}

	/**
	 * @return the inventory
	 */
	public Inventory getInventory() {
		return inventory;
	}

	/**
	 * @param inventory
	 *            the inventory to set
	 */
	public void setInventory(Inventory inventory) {
		this.inventory = inventory;
	}
	private String code;

	

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}
	private String timepart_;

	public String getTimepart_() {
		return timepart_;
	}

	public void setTimepart_(String timepart_) {
		this.timepart_ = timepart_;
	}

	public Date getBeginDate() {
		return beginDate;
	}

	public void setBeginDate(Date beginDate) {
		this.beginDate = beginDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getBeginDateString() {
		return DateUtils.format(beginDate, "yyyy-MM-dd");
	}

	public void setBeginDateString(String beginDateString) {
		this.beginDateString = beginDateString;
	}

	public String getEndDateString() {
		return DateUtils.format(endDate, "yyyy-MM-dd");
	}

	public void setEndDateString(String endDateString) {
		
		this.endDateString =endDateString;
	}

	public String getLastInventoryOperation() {
		return lastInventoryOperation;
	}

	public void setLastInventoryOperation(String lastInventoryOperation) {
		this.lastInventoryOperation = lastInventoryOperation;
	}

}
